package com.esms.controller;

import com.esms.dao.EmployeeCustomVoMapper;
import com.esms.dao.EmployeeMapper;
import com.esms.po.Employee;
import com.esms.po.WeekCheckGrand;
import com.esms.po.WeekRecordInfoMent;
import com.esms.po.WeekResultInfoMent;
import com.esms.service.impl.EmployeeWeekCheckServerImpl;
import com.esms.service.impl.EmployeeWeekServerImpl;
import com.esms.utils.DateUtil;
import com.esms.utils.Message;
import com.esms.vo.EmployeeCustomVo;
import com.esms.vo.EmployeePages;
import com.esms.vo.EmployeeWeekCheckGrandVO;
import com.esms.vo.EmployeeWeekGrandVO;
import com.esms.vo.EmployeeWeekResultPages;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author : [ko]
 * @version : [v1.0]
 * @description : [周纪实审核处理Controller]
 * @createTime : [2022/3/5 0:14]
 * @updateUser : [ko]
 * @updateTime : [2022/3/5 0:14]
 * @updateRemark : [说明本次修改内容]
 */
@Controller
@RequestMapping("/employeeWeekCheck")
public class EmployeeWeekCheckController {

	@Autowired
	private EmployeeMapper employeeMapper = null;

	@Autowired
	private EmployeeCustomVoMapper employeeCustomVoMapper = null;

	@Autowired
	private EmployeeWeekServerImpl employeeWeekServerImpl;

	@Autowired
	private EmployeeWeekCheckServerImpl employeeWeekCheckServerImpl;

	@RequestMapping("/findSelective.do")
	@ResponseBody
	public EmployeePages findSelective(
			@RequestParam(value = "page", defaultValue = "1") int pageNum,
			@RequestParam(value = "limit", defaultValue = "5") int limit,
			@RequestParam(value = "e_account", defaultValue = "") String e_account,
			@RequestParam(value = "e_name", defaultValue = "") String e_name,
			@RequestParam(value = "d_id", defaultValue = "0") int d_id,
			HttpSession httpSession) throws Exception {

		int eId = (Integer) httpSession.getAttribute("employeeId");
		Employee employee = employeeMapper.selectByPrimaryKey(eId);
		String cAccount = employee.geteAccount();// 当前登录员工工号,作为查询下属的入参
		//标题设置：当前日期上个月
		String befMouth = DateUtil.getBefMonthForNowDay();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("e_account", e_account);
		map.put("e_name", e_name);
		map.put("d_id", d_id);
		map.put("e_level", cAccount);
		//map.put("x_check_BeMonth", befMouth);//再加一个考核的月数
		List<EmployeeCustomVo> list = new ArrayList<EmployeeCustomVo>();
		try{
			//pageNum:起始页面  pageSize:每页的大小
			PageHelper.startPage(pageNum, limit);
			//查找条件，一定要紧跟在startPage后
			/**
			 * select *
			 *         from
			 *         employee e
			 *         left join department d on e.d_id = d.d_id
			 *         left join position p on e.p_id = p.p_id
			 *         left join rank_bonus rb on e.e_rank = rb.rb_id
			 *         left join x_weekResult we on e.e_id = we.x_staff_eId
			 * where e.e_level='6001';
			 * **/
			list = employeeCustomVoMapper.selectEmployeeWeekCheckSelective(map);

			for(int k=0;k<list.size();k++) {
				if(list.get(k).getWeekrment() != null){
					if(!befMouth.equals(list.get(k).getWeekrment().getxCheckBeMonth())){
						list.remove(k);
						k--;
					}
				}
			}
			/**  下面的方式不可行，使用上面去remove
			for(EmployeeCustomVo employeeCustomVo:list){
				if(employeeCustomVo.getWeekrment() != null){
					if(!befMouth.equals(employeeCustomVo.getWeekrment().getxCheckBeMonth())){
						list.remove(employeeCustomVo);
					}
				}
			}
			 **/
		}catch (Exception e){
			e.printStackTrace();
		}
		PageInfo pageResult = new PageInfo(list);
		//设置前台需要的数据
		EmployeePages employeePages = new EmployeePages();
		employeePages.setCode(0);
		employeePages.setMsg("");
		employeePages.setCount((int) pageResult.getTotal());
		employeePages.setData(pageResult.getList());
		return employeePages;
	}


	/**
	 * 查找被审核员工填写的周纪实信息,用于前端的展示，最终需要审核人员进行审核打分：
	 * 因为审核人员只有每个月初对上个月的员工周纪实进行评价，
	 * 所以此处一定要获取员工上个月的4条周纪实内容进行展示即可
	 * @param byEId   被考核员工的ID
	 * @param byDId   被考核员工的部门ID
	 * @param byEAccount   被考核员工的工号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findEmpWeekInfoSelective.do")
	@ResponseBody
	public EmployeeWeekGrandVO findDempSelective(
			@RequestParam(value="page", defaultValue="1")int pageNum,
			@RequestParam(value="limit", defaultValue="5") int limit,
			@RequestParam String byEId,
			@RequestParam String byDId,
			@RequestParam String byEAccount,
			HttpSession httpSession) throws Exception {

		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		int eId = (Integer) httpSession.getAttribute("employeeId");//当前登陆者的ID

		WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();

		//标题设置：当前日期上个月
		String befMouth = DateUtil.getBefMonthForNowDay();

		wWeekMent.setwAccount(byEAccount);//被评价员工工号
		wWeekMent.setwDId(Integer.valueOf(byDId));//被评价员工部门
		wWeekMent.setwWeekMonYear(befMouth);//该员工第几个月的周纪实，获取当前日期上个月的周纪实
		//wWeekMent.setwFlag(wFlag);
		//wWeekMent.setwFinshLivel(wFinshLivel);

		List<WeekRecordInfoMent> weekInfoListNew = new ArrayList<WeekRecordInfoMent>();
		try {
			List<WeekRecordInfoMent> weekInfoList = employeeWeekServerImpl.getEmpDeployeeWeekList(wWeekMent);
			if(weekInfoList.size()>0){
				for(WeekRecordInfoMent weekRecordInfoMent:weekInfoList){
					String weekInfo = weekRecordInfoMent.getwWeekInfo();
					String wTempOraryInfo = weekRecordInfoMent.getwTempOraryInfo();
					if(StringUtil.isNotEmpty(weekInfo)){
						weekRecordInfoMent.setwWeekInfo(Text2Html(weekInfo));//重要转换
					}
					if(StringUtil.isNotEmpty(wTempOraryInfo)){
						weekRecordInfoMent.setwTempOraryInfo(Text2Html(wTempOraryInfo));//重要转换
					}
					weekInfoListNew.add(weekRecordInfoMent);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//设置前台需要的数据
		EmployeeWeekGrandVO employeeWeekGrandVO = new EmployeeWeekGrandVO();
		employeeWeekGrandVO.setCode(0);
		employeeWeekGrandVO.setMsg("");
		employeeWeekGrandVO.setCount(weekInfoListNew.size());
		employeeWeekGrandVO.setData(weekInfoListNew);
		return employeeWeekGrandVO;
	}


	/**
	 * 打印员工审核成绩查询接口主要查询被审核员工的分数、月数、月起始和截止日期
	 * @param byEId   被考核员工的ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findWeekResultInfoSelective.do")
	@ResponseBody
	public EmployeeWeekResultPages findWeekResultInfoSelective(
			@RequestParam(value="page", defaultValue="1")int pageNum,
			@RequestParam(value="limit", defaultValue="5") int limit,
			@RequestParam String byEId,
			HttpSession httpSession) throws Exception {

		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		int eId = (Integer) httpSession.getAttribute("employeeId");//当前登陆者的ID

		WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();

		//标题设置：当前日期上个月
		String befMouth = DateUtil.getBefMonthForNowDay();

		Employee employee = employeeMapper.selectByPrimaryKey(eId);
		String cAccount = employee.geteAccount();// 当前登录员工工号,作为查询下属的入参

		WeekResultInfoMent weekResultInfoMent = new WeekResultInfoMent();
		weekResultInfoMent.setxStaffEId(Integer.valueOf(byEId));//被审核员工的ID
		weekResultInfoMent.setxSuperEId(eId);//审核员工的ID
		weekResultInfoMent.setxCheckBeMonth(befMouth);

		List<WeekResultInfoMent> list = new ArrayList<WeekResultInfoMent>();
		try{
			//pageNum:起始页面  pageSize:每页的大小
			PageHelper.startPage(pageNum, limit);
			//查找条件，一定要紧跟在startPage后

			list = employeeWeekCheckServerImpl.findWeekResultInfoSelective(weekResultInfoMent);

		}catch (Exception e){
			e.printStackTrace();
		}
		PageInfo pageResult = new PageInfo(list);
		//设置前台需要的数据
		EmployeeWeekResultPages employeeWeekResultPages = new EmployeeWeekResultPages();
		employeeWeekResultPages.setCode(0);
		employeeWeekResultPages.setMsg("");
		employeeWeekResultPages.setCount((int) pageResult.getTotal());
		employeeWeekResultPages.setData(pageResult.getList());
		return employeeWeekResultPages;
	}

	@RequestMapping("/addWeekCheckInfo.do")
	@ResponseBody
	public Message addWeekCheckInfo(
			@RequestParam("list") String listWeekCheck,
			@RequestParam String byEId,
			HttpSession httpSession) throws Exception {
		int req = 0;
		String reMsg = "";
		ObjectMapper mapper = new ObjectMapper();
		// Date date = new Date();
		Timestamp date = new Timestamp(new Date().getTime());
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		//01-当前登录员工信息
		Integer eId = (Integer) httpSession.getAttribute("employeeId");
		Employee employee = employeeMapper.selectByPrimaryKey(eId);
		//02-被审核者的员工信息
		Employee byEmployee = employeeMapper.selectByPrimaryKey(Integer.valueOf(byEId));

		try {
			JavaType weekJt = mapper.getTypeFactory().constructParametricType(ArrayList.class, WeekCheckGrand.class);
			List<WeekCheckGrand> listWeekCheckGrand = (List<WeekCheckGrand>) mapper.readValue(listWeekCheck, weekJt);

			for (int i = 0; i < listWeekCheckGrand.size(); i++) {
				WeekCheckGrand weekCheckGrand = listWeekCheckGrand.get(i);

				//1-下面两个是领导审核的日期，领导月初审核上个月一整月的周纪实
				String xCreateQuarter = DateUtil.GetQuarterByDate(formatter.format(currentTime));// 计算当前日期属于第几季度:领导审核的日期
				String xCreateWeek = DateUtil.getWeek(formatter.format(currentTime));// 计算当前日期属于哪年哪个月的第几周,例如：2022-2-5

				//所以在这里，需要找出上个月的月数，以及上个月一整月的起始日期
				//标题设置：当前日期上个月
				String beMonth = DateUtil.getBefMonthForNowDay();//上个月的月数2
				String beMonthDay = DateUtil.getBeforeMonDay();//上个月开始日期和结束日期

				WeekResultInfoMent weekResultInfoMent = new WeekResultInfoMent();
				weekResultInfoMent.setxStaffEId(Integer.valueOf(byEId));//被审核员工的ID
				weekResultInfoMent.setxSuperEId(eId);//审核员工的ID
				List<WeekResultInfoMent> empWeekResultList = employeeWeekCheckServerImpl.getEmpWeekResultList(weekResultInfoMent);
				if(empWeekResultList.size()>0){
					//直接修改即可

					//String xCheckState = weekCheckGrand.getxCheckState();//被审核员工状态
					String xCheckScore = weekCheckGrand.getxCheckScore();//被审核员工分数
					String xCheckResult = weekCheckGrand.getxCheckResult();//被审核员工审核结果描述

					weekResultInfoMent.setxCheckScore(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxCheckScoresum(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxCheckScorecalu(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxCreateQuarter(xCreateQuarter);
					weekResultInfoMent.setxCreateWeek(xCreateWeek);
					weekResultInfoMent.setxCheckBeMonth(beMonth);
					weekResultInfoMent.setxCheckBeMonthDay(beMonthDay);
					weekResultInfoMent.setxCheckResult(xCheckResult);
					weekResultInfoMent.setxCheckState("1");
					weekResultInfoMent.setxUpdateTime(date);

					//直接修改即可
					req = employeeWeekCheckServerImpl.updateByPrimaryKeySelective(weekResultInfoMent);

				}else{

					// 就是2022年2月份第五周

					String xStaffEId = weekCheckGrand.getxStaffEId();//被审核员工ID
					//String xCheckState = weekCheckGrand.getxCheckState();//被审核员工状态
					String xCheckScore = weekCheckGrand.getxCheckScore();//被审核员工分数
					String xCheckResult = weekCheckGrand.getxCheckResult();//被审核员工审核结果描述
					//先判断是否已经存在了，根据评价者的ID和被评价者的ID查询即可

					System.out.println("xStaffEId=" + xStaffEId);
					//System.out.println("xCheckState=" + xCheckState);
					System.out.println("xCheckScore=" + xCheckScore);
					System.out.println("xCheckResult=" + xCheckResult);

					/**
					 if (StringUtil.isEmpty(weekInfo.trim())) {// 如果内容为空，直接比那里下一条
					 continue;
					 }
					 **/

					weekResultInfoMent.setxId(null);
					weekResultInfoMent.setxStaffEId(Integer.valueOf(xStaffEId));
					weekResultInfoMent.setxSuperEId(eId);
					weekResultInfoMent.setxCheckState("1");
					weekResultInfoMent.setxCheckResult(xCheckResult);
					weekResultInfoMent.setxCreateTime(date);
					weekResultInfoMent.setxUpdateTime(date);
					weekResultInfoMent.setxCreateQuarter(xCreateQuarter);
					weekResultInfoMent.setxCreateWeek(xCreateWeek);
					weekResultInfoMent.setxCheckBeMonth(beMonth);
					weekResultInfoMent.setxCheckBeMonthDay(beMonthDay);
					weekResultInfoMent.setxCheckScore(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxCheckScoresum(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxCheckScorecalu(Integer.valueOf(xCheckScore));
					weekResultInfoMent.setxByzd("");
					weekResultInfoMent.setxByzd1("");
					weekResultInfoMent.setxByzd2("");
					// req = employeeWeekServerImpl.deleteWeekInfo(wWeekMent);
					req = employeeWeekCheckServerImpl.insertWeekCheckInfo(weekResultInfoMent);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (req < 0) {
			return Message.fail();
		} else {
			//审核成功，需要修改一下呗审核员工周纪实数据的审核状态，因为初始入库的是0未审核，需要更新成1已审核
			// 重新设置修改时间
			WeekRecordInfoMent weekRecordInfoMent = new WeekRecordInfoMent();
			weekRecordInfoMent.setwAccount(byEmployee.geteAccount());
			weekRecordInfoMent.setwCheckStatus("1");
			employeeWeekServerImpl.updateByWaccountSelective(weekRecordInfoMent);


			return Message.success("周纪实审核提交成功");
		}
	}


	/**
	 * 查找被审核员工填写的周纪实信息,用于前端的展示，最终需要审核人员进行审核打分
	 * @param byEId   被考核员工的ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findEmpWeekResultInfoSelective.do")
	@ResponseBody
	public EmployeeWeekCheckGrandVO findEmpWeekResultInfoSelective(
			@RequestParam(value="page", defaultValue="1")int pageNum,
			@RequestParam(value="limit", defaultValue="5") int limit,
			@RequestParam String byEId,
			HttpSession httpSession) throws Exception {

		//当前登陆者的ID,就是审核者的ID
		int eId = (Integer) httpSession.getAttribute("employeeId");

		WeekResultInfoMent weekResultInfo = new WeekResultInfoMent();

		weekResultInfo.setxStaffEId(Integer.valueOf(byEId));//被审核员工的ID
		weekResultInfo.setxSuperEId(eId);//审核员工的ID

		List<WeekResultInfoMent> weekCheckInfoListNew = new ArrayList<WeekResultInfoMent>();
		try {
			List<WeekResultInfoMent> weekInfoList = employeeWeekCheckServerImpl.getEmpWeekResultList(weekResultInfo);
			if(weekInfoList.size()>0){
				for(WeekResultInfoMent weekResultInfoMent:weekInfoList){
					String weekcheckInfo = weekResultInfoMent.getxCheckResult();
					weekCheckInfoListNew.add(weekResultInfoMent);
					/**
					if(StringUtil.isNotEmpty(weekcheckInfo)){
						weekResultInfoMent.setxCheckResult(Text2Html(weekcheckInfo));
						weekCheckInfoListNew.add(weekResultInfoMent);
					}
					 **/
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//设置前台需要的数据
		EmployeeWeekCheckGrandVO employeeWeekCheckGrandVO = new EmployeeWeekCheckGrandVO();
		employeeWeekCheckGrandVO.setCode(0);
		employeeWeekCheckGrandVO.setMsg("");
		employeeWeekCheckGrandVO.setCount(weekCheckInfoListNew.size());
		employeeWeekCheckGrandVO.setData(weekCheckInfoListNew);
		return employeeWeekCheckGrandVO;
	}


	public static String Text2Html(String str) {
		if (str == null) {
			return "";
		}else if (str.length() == 0) {
			return "";
		}
		str = str.replaceAll("\n", "<br />");
		str = str.replaceAll("\r\n", "<br />");//windows下是\n，linux下是\r\n
		return str;
	}


}
